package controller;

import controller.entity.Page;
import controller.entity.Result;
import controller.entity.RoleId;
import controller.entity.Tables;
import dto.AccordionDTO;
import entity.User;
import entity.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import service.UserService;
import service.entity.LimitUser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by asus on 2017/6/18.
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired private UserService userService;


    @RequestMapping("/index")
    public ModelAndView userList(ModelAndView mav, HttpServletRequest request, HttpServletResponse response){
        List<AccordionDTO> accordionDTOS = (List<AccordionDTO>) request.getAttribute("accordionDTOS");
        mav.addObject("accordions", accordionDTOS);
        mav.setViewName("userManage");
        return mav;
    }

    @RequestMapping("/addEditUser")
    @ResponseBody
    public Result addEditUser(User user){
        try {
            if (null == user.getId()) {
                userService.addUser(user);
            } else {
                userService.updateUser(user);
            }
            return Result.success();
        }catch (Exception e){
            return Result.fail("操作失败");
        }

    }

    @RequestMapping("/deleteUser")
    @ResponseBody
    public Result deleteUser(Long id){
        try {
            userService.deleteUserById(id);
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("删除用户失败");
        }

    }

    @RequestMapping("/getUsers")
    @ResponseBody
    public Collection<User> getUsers(Integer page, Integer size){
        return userService.getUsers(page, size);
    }

    @RequestMapping("/list")
    @ResponseBody
    public Tables getLimitUsers(@RequestParam(value="page",required = false) String page,
                        @RequestParam(value="rows", required=false) String rows,
                        @RequestParam(value="title", required=false) String title,
                                HttpServletRequest request){
        Integer pageNum=1;
        Integer rowsNum=20;//默认每行记录数
        try{
            pageNum=Integer.parseInt(page);
        }catch (Exception e){}
        try {
            rowsNum=Integer.parseInt(rows);
        }catch (Exception e){}
        Page pageBean=new Page(pageNum,rowsNum,1);
        Tables tables=new Tables();
        tables.setTotal(userService.getCount());
        tables.setRows(userService.getLimitUser((String) request.getSession().getAttribute("username"),pageNum,rowsNum));
        tables.setTitles(title);
        tables.setMethodName("getLimitUsers");
        System.out.println("pageBean:"+pageBean);
        System.out.println("tables:"+tables);
        return tables;
    }

    //TODO 目前还是写死的，只适用于将“登记员”转化为“普通雇员”
    @RequestMapping("/down")
    @ResponseBody
    public Result toLowerRole(LimitUser user){
        System.out.println("limitUser:"+user);
        List<Long> roleIds=new ArrayList<>();
        try{
            List<UserRole> userRoles = userService.getUserRolesByUserId(user.getId());
            for(UserRole userRole:userRoles){
                if(userRole.getRoleId()== RoleId.REGISTRAR){
                    roleIds.add(RoleId.NORMAL);//

                }else{
                    roleIds.add(userRole.getRoleId());
                }
            }
            userService.updateUserRole(user.getId(),roleIds.toArray(new Long[roleIds.size()]));
            return Result.success();
        }catch (Exception e){
            return Result.fail("角色转换失败！");
        }

    }

    //TODO 目前还是写死的，只适用于将“普通雇员”转化为“登记员”
    @RequestMapping("/upper")
    @ResponseBody
    public Result toUpperRole(LimitUser user){
        System.out.println("limitUser:"+user);
        List<Long> roleIds=new ArrayList<>();
        try{
            List<UserRole> userRoles = userService.getUserRolesByUserId(user.getId());
            for(UserRole userRole:userRoles){
                if(userRole.getRoleId()== RoleId.NORMAL){
                    roleIds.add(RoleId.REGISTRAR);

                }else{
                    roleIds.add(userRole.getRoleId());
                }
            }
            userService.updateUserRole(user.getId(),roleIds.toArray(new Long[roleIds.size()]));
            return Result.success();
        }catch (Exception e){
            return Result.fail("角色转换失败！");
        }
    }
}
